<template>
  <div class="export_batch">
    <Row type='flex'
         justify="center"
         style="margin-top:55px; padding-bottom: 20px">
      <Col>
      <div class="export_box">
        <div class="export_box_steps">
          <Steps :current="currentIndex">
            <Step title="上传文件"></Step>
            <Step title="执行导入"></Step>
            <Step title="导入完成"></Step>
          </Steps>
        </div>
        <div class="export_box_steps1"
             v-if="currentIndex===0">
          <Row type='flex'
               align='middle'
               class="step">
            <Col class="icon">
            <i class="iconsys icondown"
               title="下载"></i>
            </Col>
            <Col>
            <div class="bold">填写导入{{title}}的信息</div>
            <div class='middle'>请按照数据模版的格式准备导入数据,模版中的表头名称不可更改,表头行不能删除</div>
            <div class="board"
                 @click="downtempalte">下载模版</div>
            </Col>
          </Row>
          <Row type='flex'
               align='middle'
               class="step">
            <Col class="icon">
            <i class="iconsys iconupload"
               title="上传"></i>
            </Col>
            <Col>
              <div class="bold">上传填好的{{title}}信息表</div>
              <div class='middle'>文件后缀名必须为xls或xlsx(即Excel格式),文件大小不得大于10M</div>
              <Upload
                    v-if="!xlsFile"
                    class="board"
                    :before-upload="handleBeforeUpload"
                    action="">
                    <p>上传文件</p>
              </Upload>
              <div v-else>
                <span>{{ xlsFile.name }}（{{ xlsFileSize }}）</span>
                <Icon @click="deleteXls" style="margin-left: 20px; cursor: pointer" type="md-close-circle"/>
              </div>
            </Col>
          </Row>
          <Row
              v-if="enmus[title].needPassword"
              type='flex'
              align='middle'
              class="step">
            <Col class="icon">
            <i class="iconsys iconpassword"
               title="密码"></i>
            </Col>
            <Col>
            <div class="bold">{{title}}初始密码（8-16位字符，不允许输入空格）</div>
            <div style="margin-top:8px">
              <Input v-model="value"
                    type="password"
                    placeholder="登录后系统会提示修改密码"
                    style="width: 300px"
                    :maxlength="16"
                    @on-keyup="filterSpace"/>
            </div>
            </Col>
          </Row>
        </div>
        <div class="export_box_steps2"
             v-if="currentIndex===1">
          <Row type='flex'
               align='middle'
               class="step">
            <Col class="icon">
            <i class="iconsys icondown"
               title="下载"></i>
            </Col>
            <Col>
            <div class="bold">本次可导入{{title}}数量</div>
            <div style="margin-top:8px">{{ veriXlsResult.successNum }}条</div>
            </Col>
          </Row>
          <Row v-if="veriXlsResult.failNum" type='flex'
               align='middle'
               class="step">
            <Col class="icon">
            <i class="iconsys iconupload"
               title="上传"></i>
            </Col>
            <Col>
            <div class="bold">本次不可导入{{title}}数量</div>
            <div style="margin-top:8px">
              <span style="margin-right:20px">{{ veriXlsResult.failNum }}条</span>
              <span class="board" @click="getCantImportXls">不可导入{{title}}列表</span>
            </div>
            </Col>
          </Row>
        </div>
        <div class="export_box_steps3"
             v-if="currentIndex===2">
          <Row type='flex'
               align='middle'
               class="step">
            <Col class="icon">
            <Icon type="ios-checkmark-circle-outline"
                  size='42'
                  style="color:#18BE6B" />
            </Col>
            <Col>
            <div class="bold">批量导入完成</div>
            <div style="margin-top:8px">成功导入{{ title }}数量：{{ importResult.successNum || 0 }}个{{ enmus[title].needPassword ? '，默认密码：' + value : '' }}</div>
            </Col>
          </Row>
        </div>
        <div class="export_bnt">
          <Button type="primary"
                  style="width:100px"
                  @click="next">{{text}}</Button>
          <Button @click="nextBack"
                  style="margin-left:20px;width:100px"
                  v-if="currentIndex===1">返回重新上传</Button>
        </div>
      </div>
      </Col>
    </Row>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { exportRole, veriRoleXls, roleXlsImport } from '@/api/system/role'
import { exportEmployee, veriEmployeeXls, employeeXlsImport } from '@/api/system/employee'
import { exportOrgList, veriOrgXls, orgXlsImport } from '@/api/system/org'
import { veriShopXls, shopXlsImport, exportShop } from '@/api/system/store'
import { blobToXls } from '@/libs/blobToXls'
import { hex_md5 } from '@/libs/md5'
export default {
  data () {
    return {
      enmus: {
        '门店': {
          veriUrl: veriShopXls,
          importUrl: shopXlsImport,
          exportUrl: exportShop,
          fileName: 'shop',
          needPassword: false
        },
        '角色': {
          veriUrl: veriRoleXls,
          importUrl: roleXlsImport,
          exportUrl: exportRole,
          fileName: 'role',
          needPassword: false
        },
        '员工': {
          veriUrl: veriEmployeeXls,
          importUrl: employeeXlsImport,
          exportUrl: exportEmployee,
          fileName: 'employee',
          needPassword: true
        },
        '组织': {
          veriUrl: veriOrgXls,
          importUrl: orgXlsImport,
          exportUrl: exportOrgList,
          fileName: 'org',
          needPassword: false
        }
      },
      name: '批量导入',
      text: '下一步',
      value: '',
      currentIndex: this.current,
      xlsFile: null,
      veriXlsResult: {},
      importResult: {}
    }
  },
  props: {
    title: {
      type: String
    },
    templateUrl: {
      type: String
    },
    current: {
      type: Number,
      default: 0
    }
  },
  computed: {
    ...mapState({
      userName: state => state.user.phoneNumber,
      merchantId: state => state.user.merchantId
    }),
    xlsFileSize () {
      let size = 0
      if (this.xlsFile) {
        size = +(this.xlsFile.size / 1024).toFixed(2)
      }
      return size + 'kb'
    }
  },
  methods: {
    next () {
      if (this.currentIndex === 0) {
        if (this.enmus[this.title].needPassword) {
          if (!this.value) {
            this.$Message.error('请输入密码')
            return
          }
          if (this.value.length < 8) {
            this.$Message.error('密码长度小于8')
            return
          }
          if (!this.checkPassword()) {
            this.$Message.error('密码至少包含英文大小写和数字')
            return
          }
        }
        if (!this.xlsFile) {
          this.$Message.error('请上传文件')
          return
        }
        this.upload().then(data => {
          this.currentIndex++
          this.text = '下一步'
          this.veriXlsResult = data
        }).catch(res => {
          this.$Message.error(res.data.error)
        })
      } else if (this.currentIndex === 1) {
        const successNum = this.veriXlsResult.successNum
        if (!successNum) {
          this.$Message.error(`本次可导入${this.title}数量为${successNum}`)
        } else {
          this.xlsImport().then(data => {
            this.currentIndex++
            this.text = '完成'
            this.importResult = data
          }).catch(res => {
            this.$Message.error(res.data.error)
          })
        }
      } else {
        this.currentIndex = 0
        this.text = '下一步'
        this.value = ''
        this.xlsFile = null
        this.$router.back()
      }
    },
    checkPassword () {
      return (this.value.match(/([a-z])+/) && this.value.match(/([0-9])+/) && this.value.match(/([A-Z])+/))
    },
    // 下载模版
    downtempalte () {
      const eleLink = document.createElement('a')
      eleLink.href = require(`../../../assets/res/xls/${this.title}导入模版.xls`)
      eleLink.download = `${this.title}导入模版.xls`
      document.body.appendChild(eleLink)
      eleLink.click()
      document.body.removeChild(eleLink)
    },
    nextBack () {
      this.currentIndex--
      this.xlsFile = null
      this.value = ''
    },
    handleBeforeUpload (file) {
      if (!/\.xlsx?$/.test(file.name)) {
        this.$Notice.warning({
          title: '请上传xls或xlsx文件'
        })
      } else if (file.size > 10485760) {
        this.$Notice.warning({
          title: '文件大小不得大于10M'
        })
      } else {
        this.xlsFile = file
      }
      return false
    },
    deleteXls () {
      this.xlsFile = null
    },
    upload () {
      return new Promise((resolve, reject) => {
        let fd = new FormData()
        fd.append('merchantId', this.merchantId)
        fd.append('file', this.xlsFile)
        const whichType = this.enmus[this.title]
        whichType.veriUrl(fd).then(res => {
          if (res.data.status === 200) {
            resolve(res.data.data)
          } else {
            reject(res)
          }
        })
      })
    },
    xlsImport () {
      return new Promise((resolve, reject) => {
        const whichType = this.enmus[this.title]
        const params = {
          merchantId: this.merchantId,
          type: 'EXCEL',
          data: this.veriXlsResult.successList
        }
        if (whichType.needPassword) {
          params.password = hex_md5(this.value)
        }
        whichType.importUrl(params).then(res => {
          if (res.data.status === 200) {
            resolve(res.data.data)
          } else {
            reject(res)
          }
        })
      })
    },
    filterSpace () {
      this.value = this.value.replace(/\s+/g, '')
    },
    getCantImportXls () {
      const type = this.enmus[this.title]
      type.exportUrl({
        fileName: type.fileName,
        type: 'EXCEL',
        exportData: this.veriXlsResult.failList || []
      }).then(res => {
        if (res.status === 200) {
          blobToXls(res.data, `不可导入${this.title}列表`)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.export_box {
  width: 640px;
  .export_box_steps {
    width: 100%;
    font-size: 14px;
    margin-bottom: 40px;
  }
  .step {
    background: #f8f8f9;
    border: 1px solid #e8eaec;
    margin-bottom: 20px;
    height: 112px;
    .icon {
      padding: 0 30px;
      .iconsys {
        font-size: 42px;
      }
    }
    .board {
      display: inline;
      cursor: pointer;
      color: #2d8cf0;
    }
    .bold {
      font-weight: bold;
      font-size: 14px;
    }
    .middle {
      margin: 5px 0;
    }
  }
  .export_box_steps1 {
    width: 100%;
  }
  .export_box_steps2 {
    width: 100%;
  }
  .export_box_steps3 {
    width: 100%;
  }
}
</style>
